package com.millstein.realtime.util;

import com.alibaba.fastjson.JSONObject;
import redis.clients.jedis.Jedis;

import java.sql.Connection;
import java.util.List;

public class DimUtil {
    /**
     * 从phoenix中读取维度数据
     * @param phoenixConn phoenix库连接
     * @param tableName 表名
     * @param id 需要查询的id值
     * @return
     */
    public static JSONObject readDimFromPhoenix(Connection phoenixConn, String tableName, String id) {
        String sql = "select * from " + tableName + " where id = ?";
        String[] args = {id};

        List<JSONObject> list = JdbcUtil.queryList(phoenixConn, sql, args, JSONObject.class);
        return list.size() == 0 ? null : list.get(0);
    }

    /**
     * 读取维度信息。如果redis中有，那么就返回redis中的数据；如果redis中没有，那么就从phoenix中获取
     * @param phoenixConn phoenix连接
     * @param redisClient redis客户端
     * @param tableName 表名
     * @param id 需要查询的id值
     * @return
     */
    public static JSONObject readDim(Connection phoenixConn, Jedis redisClient, String tableName, String id) {
        JSONObject dim = readDimFromRedis(redisClient, tableName, id);
        if (dim == null) {
            dim = readDimFromPhoenix(phoenixConn, tableName, id);
            writeDimToRedis(redisClient, tableName, id, dim);
        }
        return dim;
    }

    /**
     * 从redis中读取维度数据
     * @param redisClient redis客户端
     * @param tableName 表名
     * @param id 需要查询的id值
     * @return
     */
    public static JSONObject readDimFromRedis(Jedis redisClient, String tableName, String id) {
        String key = tableName + ":" + id;
        String jsonString = redisClient.get(key);
        if (jsonString != null) {
            return JSONObject.parseObject(jsonString);
        }
        return null;
    }

    /**
     * 将维度数据写到redis中去
     * @param redisClient redis客户端
     * @param tableName 表名
     * @param id 需要查询的id值
     * @param dim 待写入的维度数据
     */
    public static void writeDimToRedis(Jedis redisClient, String tableName, String id, JSONObject dim) {
        String key = tableName + ":" + id;
        redisClient.setex(key, 60 * 60 * 2, dim.toJSONString());
    }
}
